import {
  AntButton as Button,
  AntFlex as Flex,
  AntList as List,
  AntPagination as Pagination,
  AntSpace as Space,
  AntSwitch as Switch,
  AntTag as Tag,
  AntTypography as Typography,
  useMessage,
} from "fidesui";
import { useRouter } from "next/router";

import { getErrorMessage, isErrorResult } from "~/features/common/helpers";
import { NOTIFICATIONS_ADD_DIGEST_ROUTE } from "~/features/common/nav/routes";
import Restrict, { useHasPermission } from "~/features/common/Restrict";
import SearchInput from "~/features/common/SearchInput";
import { DigestType, ScopeRegistryEnum } from "~/types/api";

import { DIGEST_TYPE_LABELS, MESSAGING_METHOD_LABELS } from "../constants";
import { useUpdateDigestConfigMutation } from "../digest-config.slice";
import { getFrequencyLabel } from "../helpers/cronHelpers";
import { useDigestConfigList } from "../hooks/useDigestConfigList";

const DigestConfigList = () => {
  const router = useRouter();
  const messageApi = useMessage();
  const {
    data,
    total,
    isLoading,
    page,
    pageSize,
    searchQuery,
    setPage,
    setPageSize,
    setSearchQuery,
    handleEdit,
    canUpdate,
  } = useDigestConfigList();

  const [updateDigestConfig] = useUpdateDigestConfigMutation();

  const canCreate = useHasPermission([ScopeRegistryEnum.DIGEST_CONFIG_CREATE]);

  const handleAddNew = () => {
    router.push(NOTIFICATIONS_ADD_DIGEST_ROUTE);
  };

  const handleToggleEnabled = async (config: any) => {
    const result = await updateDigestConfig({
      config_id: config.id,
      digest_config_type: DigestType.MANUAL_TASKS,
      data: {
        name: config.name,
        description: config.description,
        digest_type: config.digest_type,
        enabled: !config.enabled,
        messaging_service_type: config.messaging_service_type,
        cron_expression: config.cron_expression,
        timezone: config.timezone,
        config_metadata: config.config_metadata,
      },
    });

    if (isErrorResult(result)) {
      messageApi.error(getErrorMessage(result.error));
      return;
    }

    messageApi.success(
      `Digest "${config.name}" ${!config.enabled ? "enabled" : "disabled"} successfully`,
    );
  };

  return (
    <div>
      {/* Header with search and add button */}
      <Flex justify="space-between" align="center" className="mb-4">
        <div className="w-1/3">
          <SearchInput
            value={searchQuery}
            onChange={(value) => setSearchQuery(value)}
          />
        </div>
        {canCreate && (
          <Button
            type="primary"
            onClick={handleAddNew}
            data-testid="add-digest-btn"
          >
            Create digest
          </Button>
        )}
      </Flex>

      {/* List */}
      <List
        loading={isLoading}
        itemLayout="horizontal"
        dataSource={data}
        locale={{
          emptyText: (
            <div className="px-4 py-8 text-center">
              <Typography.Paragraph type="secondary">
                No digest configurations yet. <br />
                <Restrict scopes={[ScopeRegistryEnum.DIGEST_CONFIG_CREATE]}>
                  Click &quot;Create digest&quot; to get started.
                </Restrict>
              </Typography.Paragraph>
            </div>
          ),
        }}
        renderItem={(config) => (
          <List.Item
            key={config.id}
            actions={
              canUpdate
                ? [
                    <Button
                      key="edit"
                      type="link"
                      onClick={() => handleEdit(config)}
                      data-testid="edit-list-btn"
                      className="px-1"
                    >
                      Edit
                    </Button>,
                  ]
                : []
            }
          >
            <List.Item.Meta
              title={config.name}
              description={
                <Space direction="vertical" size={4}>
                  <Space size={4}>
                    <Tag>{DIGEST_TYPE_LABELS[config.digest_type]}</Tag>
                    <Tag>
                      {MESSAGING_METHOD_LABELS[config.messaging_service_type]}
                    </Tag>
                  </Space>
                </Space>
              }
            />
            <Flex align="center" gap={24}>
              <Typography.Text>
                {getFrequencyLabel(config.cron_expression)}
              </Typography.Text>
              {canUpdate && (
                <Switch
                  checked={config.enabled}
                  onChange={() => handleToggleEnabled(config)}
                  size="small"
                  data-testid="toggle-enabled-switch"
                />
              )}
            </Flex>
          </List.Item>
        )}
      />

      {/* Pagination */}
      {total > pageSize && (
        <Flex justify="end" className="mt-4">
          <Pagination
            current={page}
            total={total}
            pageSize={pageSize}
            onChange={(newPage, newPageSize) => {
              setPage(newPage);
              if (newPageSize !== pageSize) {
                setPageSize(newPageSize);
              }
            }}
            showSizeChanger
            showTotal={(totalItems) => `Total ${totalItems} items`}
          />
        </Flex>
      )}
    </div>
  );
};

export default DigestConfigList;
